package cn.com.dwr.modules.app.controller;

import cn.com.dwr.common.lang.Result;
import cn.com.dwr.entity.AppCartItem;
import cn.com.dwr.modules.app.annotation.Login;
import cn.com.dwr.service.AppCartItemService;
import cn.com.dwr.service.AppUserService;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/app/cart")
public class CartItemController {

    @Resource
    AppCartItemService appCartItemService;

    @Resource
    AppUserService appUserService;

    /**
     * 购物车-列表
     * @return
     */
    @Login
    @GetMapping("/list")
    public Result list(){
        return Result.success(appCartItemService.getCurrent());
    }

    /**
     * 购物车-商品数量
     * @return
     */
    @Login
    @GetMapping("/count")
    public Result count(){
        return Result.success(appCartItemService.getCount());
    }

    /**
     * 购物车-商品总金额
     * @return
     */
    @Login
    @GetMapping("/total")
    public Result total(@RequestBody Long[] ids){
        return Result.success(appCartItemService.getTotal(ListUtil.toList(ids)));
    }

    /**
     * 购物车-修改数量
     * @param id
     * @param quantity
     * @return
     */
    @Login
    @PostMapping("/updateQuantity")
    public Result updateQuantity(Long id, Integer quantity){
        appCartItemService.updateQuantity(id, quantity);
        return Result.success();
    }

    /**
     * 加入购物车
     * @param appCartItem
     * @return
     */
    @Login
    @PostMapping("/add")
    public Result add(@Validated @RequestBody AppCartItem appCartItem){
        appCartItemService.add(appCartItem);
        return Result.success();
    }

    /**
     * 删除购物车
     * @param ids
     * @return
     */
    @Login
    @PostMapping("/delete")
    public Result delete(@RequestBody Long[] ids){
        long userId = appUserService.getCurrentUserId();
        appCartItemService.remove(new QueryWrapper<AppCartItem>()
                .eq("user_id", userId)
                .in("id", ListUtil.toList(ids)));
        return Result.success();
    }
}
